package Servlet;

import vo.ResultBean;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@WebServlet("/upload")
public class UploadImageServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		ResultBean resultBean = ResultBean.ERROR("上传失败");

		//判断上传的表单是否是一个带有上传文件的表单
		if (ServletFileUpload.isMultipartContent(req)) {
			try {
				//将请求体中表单的内容转换成表单项集合
				List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);

				//遍历表单项
				for (FileItem item : multiparts) {
					//判断是否一个常规表单项 (输入框  密码框 下拉列表)
					if (!item.isFormField()) {
						//进来说明是文件上传表单项   aa.png
						String fileName = new File(item.getName()).getName();
						//重命名  hsahsdkajdksadksal37213hjdsajaa.png
						fileName = UUID.randomUUID().toString().replaceAll("-","")+fileName;

						//将文件上传到七牛云
						Configuration cfg = new Configuration(Region.region0());
						cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
						UploadManager uploadManager = new UploadManager(cfg);
						String accessKey = "YG5mNo8xmrQZgrFVALdnDdnK3sZ5d-lBlqqFFXXU";
						String secretKey = "xGKWrfjmnfbID4RhL0EoO2LoFmteCY83DrVUO7S8";
						String bucket = "elm2024";

						Auth auth = Auth.create(accessKey, secretKey);
						String upToken = auth.uploadToken(bucket);
						//上传
						Response response = uploadManager.put(item.getInputStream(), fileName, upToken,null,null);
						if(response.statusCode==200){
							resultBean = ResultBean.SUCCESS("http://smk4ysaa0.hd-bkt.clouddn.com/"+fileName);
						}
					}
				}
			} catch (Exception e) {
				resultBean.setMsg(e.getMessage());
			}
		} else {
			resultBean.setMsg("您提交的表单没有文件");
		}

		resp.getWriter().write(JSONObject.toJSONString(resultBean));
	}
}

